import { _decorator, Component, Node, ProgressBar, tween, Tween } from 'cc';

const { ccclass, property, requireComponent } = _decorator;

/**
 * 进度条动画控制器
 */
@ccclass('ScrollProgressBar')
@requireComponent(ProgressBar)
export default class ScrollProgressBar extends Component {

    @property(ProgressBar)
    private readonly target: ProgressBar;

    private _isUpdate: boolean = false;
    private _value: { from: number, to: number, current: number } = { from: 0, to: 0, current: 0 };

    /** 当前值，直接赋值会立即刷新当前值，不会进行滚动 */
    set value(v: number) {
        this._value.from = v;
        this._value.to = v;
        this._value.current = v;
        this._setValue();
    }
    get value() {
        return this._value.current;
    }

    onLoad() {
        this.value = this.target.progress || 0;
    }

    onDestroy() {
        Tween.stopAllByTarget(this._value);
    }

    update(dt: number) {
        if (!this._isUpdate) return;
        this._value.current = this._value.from;
        this._setValue();
    }

    /**
     * 滚动到目标值
     * @param duration 
     * @param value 
     */
    scrollTo(duration: number, value: number) {
        this._value.to = value;
        if (this._value.to !== this._value.from) {
            this._isUpdate = true;
            Tween.stopAllByTarget(this._value);
            tween(this._value)
                .to(duration, { from: this._value.to })
                .call(() => {
                    this._isUpdate = false;
                    this._value.from = this._value.to;
                    this._value.current = this._value.to;
                    this._setValue();
                })
                .start();
        }
    }

    private _setValue() {
        this.target.progress = this.value;
    }
}
